<template>
  <!-- 
    v-if="notamStore.count > 0"
   -->
  <!-- v-loading="isLoading" -->
  <el-badge :value="targetData.length" class="bounceIn">
    <div
      class="card-wrapper notam-card"
      @contextmenu.prevent="announcement(true)"
      @mousemove="isHovering = true"
      @mouseout="isHovering = false"
    >
      <div class="closure-title" v-if="showContent">
        <span>跑道关闭</span>
        <el-dropdown @command="handleCommand">
          <span class="closure-date">
            <span>{{ targetDateString }}</span>
            <span class="closure-date-day">
              <!-- <span v-if="diffTargetToday == 0">今</span>
              <span v-else-if="diffTargetToday > 0">昨</span>
              <span v-else-if="diffTargetToday < 0">明</span> -->
              {{ target.substring(0, 1) }}
            </span>
            <el-icon>
              <CaretBottom />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-item command="昨日">昨日</el-dropdown-item>
            <el-dropdown-item command="今日">今日</el-dropdown-item>
            <el-dropdown-item command="明日">明日</el-dropdown-item>
          </template>
        </el-dropdown>
      </div>
      <!-- SIPDS 数据已中断 -->
      <div
        class="closure-content closure-content-error"
        v-if="isReal && (disabled || versionDiff > 60)"
      >
        <!-- class="vibrate-hard" -->
        <el-icon :size="54"><CircleCloseFilled /></el-icon>
        <div style="padding: 6px 0">SIPDS 数据已中断</div>
      </div>
      <!-- Content -->
      <div class="closure-content" v-else-if="showContent">
        <el-scrollbar height="100%">
          <div
            v-for="closure in targetData"
            :class="[
              'closure-content-line',
              dayjs().isBefore(closure.end) && dayjs().isAfter(closure.start)
                ? '' // vibrate?
                : '',
            ]"
            :style="{ opacity: dayjs().isAfter(closure.end) ? '0.5' : '1' }"
            @click="showDetail"
          >
            <b>{{ closure.runways.join("、") }}</b>
            <span
              v-if="
                targetDateObject.isAfter(closure.start, 'day') &&
                targetDateObject.isBefore(closure.end, 'day')
              "
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <!-- <el-icon class="vibrate-slight"><QuestionFilled /></el-icon> -->
              <!-- <el-icon class="vibrate-slight"><RemoveFilled /></el-icon> -->
              <!-- <el-icon class="vibrate-slight"><CircleCloseFilled /></el-icon> -->
              <span style="padding-left: 2px"
                >至{{ -targetDateObject.diff(closure.end, "day") }}天后</span
              >
            </span>
            <span v-else>
              <span v-if="targetDateObject.isAfter(closure.start, 'day')"
                >前日</span
              >
              <!-- 0000 -->
              <span v-else> {{ dayjs(closure.start).format("HHmm") }}</span>
              <span>~</span>
              <span v-if="targetDateObject.isBefore(closure.end, 'day')"
                >次日</span
              >
              <!-- 2359 -->
              <span v-else> {{ dayjs(closure.end).format("HHmm") }}</span>
            </span>
          </div>
          <div
            v-if="target == '明日' && !isTodayEnded"
            class="closure-content-line vibrate-slight"
            style="justify-content: center"
            @click="handleCommand('今日')"
          >
            <el-icon><ArrowLeftBold /></el-icon>
            <!-- <el-icon><WarnTriangleFilled /></el-icon> -->
            <!-- <el-icon class="blinking-slight"><BellFilled /></el-icon> -->
            <span style="padding-left: 2px">今日跑道关闭未结束</span>
          </div>
          <div
            v-if="target == '今日'"
            class="closure-content-line"
            style="justify-content: center"
            @click="handleCommand('明日')"
          >
            <span style="padding-right: 2px">查看明日</span>
            <el-icon><ArrowRightBold /></el-icon>
          </div>
          <div
            v-if="target == '昨日'"
            class="closure-content-line"
            style="justify-content: center"
            @click="handleCommand('今日')"
          >
            <span style="padding-right: 2px">查看今日</span>
            <el-icon><ArrowRightBold /></el-icon>
          </div>
        </el-scrollbar>
      </div>
      <div
        v-if="showContent"
        :class="[
          'closure-footer',
          isHovering ? 'closure-notify' : 'closure-version',
        ]"
      >
        <div
          :class="[
            'closure-footer-content',
            'closure-notify-content',
            isHovering ? '' : 'closure-notify-content-hide',
          ]"
          @click="showDetail"
        >
          点击此处查看原文
        </div>
        <div
          :class="[
            'closure-footer-content',
            'closure-version-content',
            isHovering ? 'closure-version-content-hide' : '',
          ]"
        >
          <span v-if="isLoading">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>
            <span>正在更新...</span>
          </span>
          <span v-else>
            <span>更新于&nbsp;</span>
            <b>{{ versionDiff }}</b>
            <span>&nbsp;分钟前</span>
          </span>
        </div>
      </div>
    </div>
  </el-badge>
</template>

<script setup>
import { h, ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import useCommonStore from "@/store/common.js";
// import useSeatStore from "@/store/seat";
import useNotamStore from "@/store/notam.js";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
const notamStore = useNotamStore();
// const seatStore = useSeatStore();
const commonStore = useCommonStore();
const isReal = computed(() => commonStore.isReal);
const disabled = computed(() => notamStore.disabled);

// const isSeatAvailable = computed(() => seatStore.isSeatAvailable);
const isHovering = ref(false);
const target = ref("明日");
const targetDateObject = computed(() => {
  if (target.value == "今日") {
    return dayjs();
  } else if (target.value == "明日") {
    return dayjs().add(1, "day");
  } else {
    return dayjs().subtract(1, "day");
  }
});
const diffTargetToday = computed(() =>
  dayjs().diff(targetDateObject.value, "day")
);
const targetDateString = computed(() => {
  // let fmt = "M月D日";
  // let fmt = "MMDD";
  let fmt = "MM/DD";
  return targetDateObject.value.format(fmt);
});
const targetData = computed(() => {
  if (target.value == "今日") {
    return notamStore.runwayClosureToday;
  } else if (target.value == "明日") {
    return notamStore.runwayClosureTomorrow;
  } else if (target.value == "昨日") {
    return notamStore.runwayClosureYesterday;
  }
});

const handleCommand = (selection) => {
  target.value = selection;
  lastSelect = new Date().getTime();
};

const versionDiff = computed(() => {
  if (!notamStore.version) return "XX";
  let diff = dayjs().diff(notamStore.version, "minutes");
  return diff > 999 ? 999 : diff;
});

const showDetail = () => {
  if (targetData.length == 0) {
    ElMessage("未找到相关NOTAM");
    return null;
  }
  let messages = [];
  for (let i = 0; i < targetData.value.length; i++) {
    let notam = targetData.value[i];
    messages.push(h("pre", { style: { padding: "6px 0" } }, notam.text));
  }
  messages.push(
    h(
      "div",
      { style: { paddingTop: "12px" } },
      `此处仅显示与${target.value}跑道关闭有关的NOTAM, 如需检索全部有效NOTAM请查看 #活动信息# 页面`
    )
  );

  ElMessageBox({
    title: `相关NOTAM (${target.value}跑道关闭)`,
    message: h("div", null, messages),
    draggable: true,
  });
};

const showContent = ref(true);
const isTodayEnded = ref(true);
let lastSelect = 0;

// 每20秒将卡片默认显示日期设置为最近的跑道关闭未完成日期
const resetContent = async () => {
  if (new Date().getTime() - lastSelect < 20 * 1000) {
    return null;
  }
  let iTargrt = "明日";
  isTodayEnded.value = true;
  for (let i = 0; i < notamStore.runwayClosureToday.length; i++) {
    let cell = notamStore.runwayClosureToday[i];
    // 当日存在未结束的关闭计划
    if (dayjs().isBefore(cell.end)) {
      isTodayEnded.value = false;
      // 开始时间在当前日期之前，结束时间在当前日期之后，则显示次日
      if (
        dayjs().isSame(cell.start, "day") ||
        dayjs().isSame(cell.end, "day")
      ) {
        iTargrt = "今日";
      }
    }
  }
  showContent.value = false;
  target.value = iTargrt;
  await nextTick();
  showContent.value = true;
};

// announcement of runway closure for Today & Tomorrow

let thresholdBefore = -20;
let announcedCodeList = new Array();
let announcing = null;
let announcingCount = 0;

const announcement = (force = false) => {
  // console.log("RWY Clusure: Check announcement", force ? " forcelly!" : "...");
  // console.log("announcedCodeList", announcedCodeList);
  announcing = new Array();
  announcingCount = 0;
  if (force) announcedCodeList = new Array();
  for (let i = 0; i < targetData.value.length; i++) {
    let cell = targetData.value[i];
    let code = cell.code;
    let before = dayjs().diff(cell.start, "minute");
    if ((before >= thresholdBefore && before <= 0) || (force && before <= 0)) {
      announcingCount++;
      if (!announcedCodeList.includes(code)) {
        announcedCodeList.push(code);
        let airport =
          (cell.airport == "ZUUU"
            ? "双流"
            : cell.airport == "ZUTF"
            ? "天府"
            : cell.airport == "ZUMY"
            ? "绵阳"
            : cell.airport == "ZULZ"
            ? "泸州"
            : cell.airport == "ZUYB"
            ? "宜宾"
            : "未知") + "机场";
        for (let j = 0; j < cell.runways.length; j++) {
          let message = airport + "即将关闭" + cell.runways[j] + "跑道";
          let audio = cell.airport + cell.runways[j].replace("/", "");
          announcing.push({ message, audio });
        }
      }
    }
  }

  // if nothing
  if (announcingCount == 0) {
    // console.log("reset announcedCodeList");
    announcedCodeList = new Array();
    return null;
  }
  if (announcing.length == 0 && announcedCodeList.length > 0) {
    console.log("ignored", announcedCodeList);
  }

  // if need for announcing
  if (announcing.length > 0) {
    ElMessageBox.close(false);
    playMessage();
    const messages = announcing.map((item) => {
      return h("p", null, item.message);
    });
    messages.push(h("p", null, "*此功能目前正在测试中"));
    messages.push(h("p", null, "*请与对应塔台席位协调并核实相关信息"));
    ElMessageBox({
      title: `跑道关闭提醒`,
      message: h("div", null, messages),
      draggable: true,
    });
  }
};

// play audio alarm
const playMessage = () => {
  let players = announcing.map((item) => {
    return new Audio(`audios/${item.audio}.ogg`);
  });
  players.unshift(new Audio("audios/Alarm.ogg"));
  players.push(new Audio("audios/Notice.ogg"));
  console.log("Going to play audio");
  for (let i = 0; i < players.length; i++) {
    players[i].onended = () => {
      players[i] = null;
      if (i + 1 < players.length) {
        console.log("Playing audio", players[i + 1].src);
        players[i + 1].play();
      } else {
        players = null;
      }
    };
  }
  console.log("Playing audio", players[0].src);
  players[0].play();
};

// loading params
let timerRefresh = null;
let timerAnnounce = null;
let intervalRefresh = 10 * 1000;
let intervalAnnounce = 10 * 1000;
const isLoading = ref(false);

onMounted(() => {
  isLoading.value = true;
  notamStore.load().then(() => {
    isLoading.value = false;
    // console.log("notamStore.load");
    resetContent();
    // if (isSeatAvailable) setAnnounceTimmer();
    if (isReal) setAnnounceTimmer();
  });
  // if (isSeatAvailable) setRefreshTimmer();
  if (isReal) setRefreshTimmer();
});
onUnmounted(() => {
  clearInterval(timerRefresh);
  clearInterval(timerAnnounce);
});

const setAnnounceTimmer = () => {
  // timer for anouncement
  if (timerAnnounce == null) {
    timerAnnounce = setInterval(() => {
      resetContent();
      announcement();
    }, intervalAnnounce);
    // console.log("NOTAM timerAnnounce setted: ", timerAnnounce);
  }
};

const setRefreshTimmer = () => {
  // timer for refresh
  if (timerRefresh == null) {
    timerRefresh = setInterval(() => {
      isLoading.value = true;
      notamStore.load().then(() => {
        isLoading.value = false;
        resetContent();
        notamStore.refresh();
        setAnnounceTimmer();
      });
    }, intervalRefresh);
    console.log("NOTAM timerRefresh setted: ", timerAnnounce);
  }
};
</script>

<style scoped>
@import "@/styles/card.css";
@import "@/styles/vibrate.css";
@import "@/styles/blinking.css";

.notam-card {
  font-size: 12px;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
  background-color: var(--theme-color-notam-card);
  overflow: hidden;
}

.closure-title {
  width: 160px;
  height: 35px;
  display: flex;
  padding: 0 12px;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}
/* .closure-date {
  width: 160px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ebb563;
  font-weight: bold;
  font-size: 12px;
  text-align: center;
} */

.closure-date {
  font-weight: bold;
  transition: all 0.3s ease-in-out;
  padding-left: 4px;
  /* display: flex; */
  /* align-items: flex-start; */
}
.closure-date:hover {
  color: #ebb563;
}

.closure-date-day {
  font-size: 10px;
  /* opacity: 0.85; */
  padding-left: 2px;
  /* padding: 2px; */
  /* transform: translateY(-4px); */
  /* background-color: #fff; */
  /* color: var(--theme-color-notam-card); */
  /* border-radius: 6px; */
  /* width: 12px; */
  /* height: 12px; */
  /* display: flex; */
  /* align-items: center; */
  /* justify-content: center; */
}
.closure-content {
  width: 160px;
  height: 100px;
  padding: 0 6px;
  /* border-top: 1px solid rgba(255, 255, 255, 0.25); */
  /* border-bottom: 1px solid rgba(255, 255, 255, 0.25); */
}

.closure-content-error {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.closure-content-line {
  width: 100%;
  padding: 3px 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid rgba(255, 255, 255, 0.25);
  transition: all 0.3s ease-in-out;
}

.closure-content-line:last-child {
  border-bottom: none;
  border-top: 1px solid rgba(255, 255, 255, 0.25);
  border-bottom: 1px solid rgba(255, 255, 255, 0.25);
}

.closure-content-line:hover {
  color: #ebb563;
}
.closure-content-null {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #fff;
  opacity: 0.5;
}

.closure-footer {
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  /* color: #574266; */
  color: var(--theme-color-notam-card);
  background-color: #fff;
  text-shadow: none;
  transition: all 0.3s ease-in-out;
  /* position: absolute; */
  /* bottom: 0; */
  height: 25px;
  /* left: 0; */
  /* right: 0; */
}
.closure-version {
  height: 25px;
  width: 120px;
  /* left: 20px; */
  /* right: 20px; */
  margin: 0;
  border-radius: 12px 12px 0 0;
  transform: scale(1);
}

.closure-notify {
  width: 140px;
  height: 20px;
  /* left: 10px; */
  /* right: 10px; */
  margin: 2px 0 3px 0;
  border-radius: 12px 12px 12px 12px;
  transform: scale(0.9);
}

.closure-footer-content {
  transition: all 0.7s ease-in-out;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.closure-version-content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
.closure-version-content-hide {
  top: 0;
  right: 0;
  height: 0;
  left: 0;
  opacity: 0;
}

.closure-notify-content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
.closure-notify-content-hide {
  height: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
}
</style>

<style>
@import "@/styles/colors.css";
</style>
